package masterlink.sarPoint.source;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

import masterlink.sarPoint.Start;
import masterlink.sarPoint.vo.Ipush;
import masterlink.sarPoint.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.icetech.quoteclient.MSG;
import com.icetech.quoteclient.jQuoteLink;
import com.icetech.quoteclient.jQuoteMsg;
public class IpushHandler extends Thread implements jQuoteMsg{
	private static final Logger log=LoggerFactory.getLogger(IpushHandler.class);
	private static Properties mini = new Properties();
	jQuoteLink quotelink;
	public void run(){
		String host = Start.getStringProperty("host","www");
		int port = Start.getIntProperty("infoport",0);
		int dataport = Start.getIntProperty("dataport",0);
		String comp = Start.getStringProperty("company","c");
		String prod = Start.getStringProperty("product","p");
		String iceuser = Start.getStringProperty("iceuser","u");
		String pass = Start.getStringProperty("password",null);
		String category = Start.getStringProperty("category","");
		String category1 = Start.getStringProperty("category1","");
		log.debug("Connecting to quoteLink: "+host+","+port+","+host+","+dataport);
		quotelink = new jQuoteLink(host,port,host,dataport);
		log.trace("jQuoteLink getted");
		quotelink.setMsgProc(this);
		log.trace("comp:"+comp+", prod:"+prod+", iceuser:"+iceuser+", pass:"+pass);
		boolean conTag=quotelink.netConnect(comp,prod,iceuser,pass);
		log.trace("jQuoteLink Connected : "+conTag);
		String path = Start.getStringProperty("path","");
		File mFile = new File(path);
		try {
			mini.load(new FileReader(mFile));
		} catch (Exception e) {
			log.error("getFileError:{}",e);
		}
		String spMonth = mini.getProperty(Util.getMonth());
		mini.clear();
		if(Util.getToday()>Integer.parseInt(spMonth)){
			spMonth=Util.getNextMonth();
		}else{
			spMonth = Util.getMonth();
		}

		if(conTag){
//			quotelink.recoverMarket(category);
			quotelink.chSubscribe(category1+spMonth);
			log.info("quoteLink connected!");
		}else{
			log.error("IPUSH Connection Fial!");
		}
	}
	@Override
	public void doQMsg(byte[] channel, int mcode, MSG qRecv, boolean isRecover) {
		if(qRecv.nVal[3]!=0){
			Start.put(createBean(qRecv));
		}
	}

	@Override
	public void onIPushStatus(int arg0, String arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onRevStatus(int arg0, String arg1) {
		// TODO Auto-generated method stub
		
	}
	private Ipush createBean(MSG qRecv){
		Ipush p=new Ipush();
		p.setsTime(qRecv.nVal[0]);//系統時間
		p.settTime(qRecv.nVal[3]);//成交時間
		p.setPrice(qRecv.nVal[16]);//成交價格
		p.setQty(qRecv.nVal[18]);//成交數量
		p.setSumqty(qRecv.nVal[19]);//累積數量
		return p;
	}
}
